<?php
// 本类由系统自动生成，仅供测试用途
namespace User\Controller;
use Think\Controller;
class AuthController extends Controller {
    public function index(){
		$this->show('User','utf-8');
    }

    protected function Succ($data)
    {
		$this->ajaxReturn(array("state" => true, "data" => $data));
    }

    protected function Fail($data)
    {
		$this->ajaxReturn(array("state" => false, "data" => $data));
    }

    // 用户登陆
    public function login()
    {
    	// 入参检查
    	$username = I('request.username');
    	if(strlen($username) < 3)
    	{
    		$this->Fail("Username is too short!");
    	}

    	$password = I('request.password');
    	if(strlen($password) < 3)
    	{
    		$this->Fail("Password is too short!");
    	}

    	$UserTable = D('User');

    	// 验证用户名是否存在
    	$result = $UserTable->field("ID, password")->where(array("username" => $username))->find();
    	$userID = -1;
    	if(empty($result))
    	{
    		// 如果不存在调用注册
    		$UserTable->create(array("username" => $username, "password" => $password));
    		$userID = $UserTable->add();
    	}
    	else
    	{
    		// 存在核对密码
    		if($password != $result["password"])
    		{
    			$this->Fail("Password is not accordinate!");
    		}

    		$userID = $result["ID"];
    	}

    	// 记入Session
    	session("userID", $userID);

    	// 返回成功
    	$this->Succ(true);
    }

    // 用户注销
    public function logout()
    {
    	// 清除Session
    	session(null);

    	// 返回成功
    	$this->Succ(true);
    }
}